/**
 * 浏览器工作流 - 选项页面脚本
 * 处理设置页面的用户交互和配置管理
 */

document.addEventListener('DOMContentLoaded', function() {
  // 获取DOM元素
  const enableExtensionEl = document.getElementById('enable-extension');
  const playbackSpeedEl = document.getElementById('playback-speed');
  const useOriginalTimingsEl = document.getElementById('use-original-timings');
  const showLogsEl = document.getElementById('show-logs');
  const highlightElementsEl = document.getElementById('highlight-elements');
  const highlightColorEl = document.getElementById('highlight-color');
  const colorPreviewEl = document.getElementById('color-preview');
  const colorTextEl = document.getElementById('color-text');
  const showFloatingButtonEl = document.getElementById('show-floating-button');
  const debugModeEl = document.getElementById('debug-mode');
  const recordScrollEl = document.getElementById('record-scroll');
  const recordKeyboardEl = document.getElementById('record-keyboard');
  const smartSelectorEl = document.getElementById('smart-selector');
  const maxActionsEl = document.getElementById('max-actions');
  const versionTextEl = document.getElementById('version-text');
  const updateTimeEl = document.getElementById('update-time');
  const statusTextEl = document.getElementById('status-text');
  const totalActionsEl = document.getElementById('total-actions');
  const saveBtnEl = document.getElementById('save-btn');
  const resetBtnEl = document.getElementById('reset-btn');
  const messageBoxEl = document.getElementById('message-box');

  // 默认配置
  const defaultConfig = {
    enableExtension: true,
    playbackSpeed: 500, // 默认回放频率500毫秒
    useOriginalTimings: true, // 默认使用原始时间间隔
    showLogs: false, // 默认关闭操作日志面板
    highlightElements: true,
    highlightColor: '#ff6b6b', // 默认高亮颜色为红色
    showFloatingButton: false,
    debugMode: false,
    recordScroll: true,
    recordKeyboard: true,
    smartSelector: true,
    maxActions: 1000
  };

  /**
   * 显示消息
   * @param {string} message - 消息内容
   * @param {string} type - 消息类型 (success, error, warning, info)
   */
  function showMessage(message, type = 'info') {
    messageBoxEl.textContent = message;
    messageBoxEl.className = `message ${type}`;
    messageBoxEl.style.display = 'block';
    
    // 3秒后隐藏消息
    setTimeout(() => {
      messageBoxEl.style.display = 'none';
    }, 3000);
  }

  /**
   * 更新颜色预览
   * @param {string} color - 颜色值
   */
  function updateColorPreview(color) {
    colorPreviewEl.style.backgroundColor = color;
    colorTextEl.textContent = color.toUpperCase();
  }

  /**
   * 更新回放频率输入框状态
   * @param {boolean} useOriginalTimings - 是否使用原始时间间隔
   */
  function updatePlaybackSpeedState(useOriginalTimings) {
    if (useOriginalTimings) {
      playbackSpeedEl.disabled = true;
      playbackSpeedEl.style.opacity = '0.5';
      playbackSpeedEl.style.cursor = 'not-allowed';
      playbackSpeedEl.title = '已启用"采用操作时间"，此设置已禁用';
    } else {
      playbackSpeedEl.disabled = false;
      playbackSpeedEl.style.opacity = '1';
      playbackSpeedEl.style.cursor = '';
      playbackSpeedEl.title = '控制回放时每个操作之间的间隔时间';
    }
  }

  /**
   * 加载设置
   */
  async function loadSettings() {
    try {
      const result = await chrome.storage.sync.get(Object.keys(defaultConfig));
      
      // 合并默认配置和已保存的配置
      const config = { ...defaultConfig, ...result };
      
      // 更新UI
      enableExtensionEl.checked = config.enableExtension;
      playbackSpeedEl.value = config.playbackSpeed;
      useOriginalTimingsEl.checked = config.useOriginalTimings;
      showLogsEl.checked = config.showLogs;
      highlightElementsEl.checked = config.highlightElements;
      highlightColorEl.value = config.highlightColor;
      updateColorPreview(config.highlightColor);
      showFloatingButtonEl.checked = config.showFloatingButton;
      debugModeEl.checked = config.debugMode;
      recordScrollEl.checked = config.recordScroll;
      recordKeyboardEl.checked = config.recordKeyboard;
      smartSelectorEl.checked = config.smartSelector;
      maxActionsEl.value = config.maxActions;
      
      // 更新回放频率输入框状态
      updatePlaybackSpeedState(config.useOriginalTimings);
      
      console.log('设置已加载:', config);
    } catch (error) {
      console.error('加载设置失败:', error);
      showMessage('加载设置失败', 'error');
    }
  }

  /**
   * 保存设置
   */
  async function saveSettings() {
    try {
      const config = {
        enableExtension: enableExtensionEl.checked,
        playbackSpeed: parseInt(playbackSpeedEl.value),
        useOriginalTimings: useOriginalTimingsEl.checked,
        showLogs: showLogsEl.checked,
        highlightElements: highlightElementsEl.checked,
        highlightColor: highlightColorEl.value,
        showFloatingButton: showFloatingButtonEl.checked,
        debugMode: debugModeEl.checked,
        recordScroll: recordScrollEl.checked,
        recordKeyboard: recordKeyboardEl.checked,
        smartSelector: smartSelectorEl.checked,
        maxActions: parseInt(maxActionsEl.value)
      };
      
      // 验证配置值
      if (config.playbackSpeed < 10) config.playbackSpeed = 10;
      if (config.playbackSpeed > 5000) config.playbackSpeed = 5000;
      if (config.maxActions < 100) config.maxActions = 100;
      if (config.maxActions > 10000) config.maxActions = 10000;
      
      // 保存到sync storage
      await chrome.storage.sync.set(config);
      
      // 通知所有content scripts更新设置
      await notifyContentScripts();
      
      showMessage('设置已保存', 'success');
      console.log('设置已保存:', config);
      
    } catch (error) {
      console.error('保存设置失败:', error);
      showMessage('保存设置失败', 'error');
    }
  }

  /**
   * 重置设置到默认值
   */
  async function resetSettings() {
    if (!confirm('确定要重置所有设置到默认值吗？')) {
      return;
    }
    
    try {
      // 清除现有设置
      await chrome.storage.sync.clear();
      
      // 保存默认设置
      await chrome.storage.sync.set(defaultConfig);
      
      // 重新加载设置到UI
      await loadSettings();
      
      // 通知content scripts
      await notifyContentScripts();
      
      showMessage('设置已重置为默认值', 'success');
      console.log('设置已重置为默认值');
      
    } catch (error) {
      console.error('重置设置失败:', error);
      showMessage('重置设置失败', 'error');
    }
  }

  /**
   * 通知所有content scripts更新设置
   */
  async function notifyContentScripts() {
    try {
      const tabs = await chrome.tabs.query({});
      const promises = tabs.map(tab => {
        if (tab.url && !tab.url.startsWith('chrome://') && !tab.url.startsWith('chrome-extension://')) {
          return chrome.tabs.sendMessage(tab.id, { type: 'UPDATE_SETTINGS' }).catch(() => {
            // 忽略无法发送消息的标签页（可能没有content script）
            console.log(`无法发送消息到标签页 ${tab.id}`);
          });
        }
        return Promise.resolve();
      });
      
      await Promise.all(promises);
      console.log('已通知所有content scripts更新设置');
    } catch (error) {
      console.error('通知content scripts失败:', error);
    }
  }

  /**
   * 更新状态信息
   */
  async function updateStatus() {
    try {
      // 更新版本信息
      const manifest = chrome.runtime.getManifest();
      versionTextEl.textContent = manifest.version;
      
      // 更新时间
      updateTimeEl.textContent = new Date().toLocaleString('zh-CN');
      
      // 检查录制状态
      const result = await chrome.storage.local.get(['isRecording', 'recordedActions']);
      
      if (result.isRecording) {
        statusTextEl.textContent = '录制中';
        statusTextEl.className = 'status-recording';
      } else {
        statusTextEl.textContent = '就绪';
        statusTextEl.className = 'status-ready';
      }
      
      // 更新已录制操作数量
      const actions = result.recordedActions || [];
      totalActionsEl.textContent = actions.length;
      
    } catch (error) {
      console.error('更新状态失败:', error);
      statusTextEl.textContent = '错误';
      statusTextEl.className = 'status-error';
    }
  }

  // 事件监听器
  saveBtnEl.addEventListener('click', saveSettings);
  resetBtnEl.addEventListener('click', resetSettings);

  // 采用操作时间复选框事件监听
  useOriginalTimingsEl.addEventListener('change', function() {
    updatePlaybackSpeedState(this.checked);
    
    // 延迟保存设置
    clearTimeout(window.saveTimeout);
    window.saveTimeout = setTimeout(() => {
      saveSettings();
    }, 1000);
  });

  // 输入值验证
  playbackSpeedEl.addEventListener('input', function() {
    const value = parseInt(this.value);
    if (value < 10) this.value = 10;
    if (value > 5000) this.value = 5000;
  });

  maxActionsEl.addEventListener('input', function() {
    const value = parseInt(this.value);
    if (value < 100) this.value = 100;
    if (value > 10000) this.value = 10000;
  });

  // 颜色选择器事件监听
  highlightColorEl.addEventListener('input', function() {
    updateColorPreview(this.value);
  });

  highlightColorEl.addEventListener('change', function() {
    updateColorPreview(this.value);
    // 颜色变化时保存设置
    clearTimeout(window.saveTimeout);
    window.saveTimeout = setTimeout(() => {
      saveSettings();
    }, 500);
  });

  // 设置变化时自动保存
  const settingElements = [
    enableExtensionEl, showLogsEl, highlightElementsEl, showFloatingButtonEl, 
    debugModeEl, recordScrollEl, recordKeyboardEl, smartSelectorEl
  ];

  settingElements.forEach(element => {
    element.addEventListener('change', function() {
      // 延迟保存，避免频繁操作
      clearTimeout(window.saveTimeout);
      window.saveTimeout = setTimeout(() => {
        saveSettings();
      }, 1000);
    });
  });

  // 数值输入框失焦时保存
  playbackSpeedEl.addEventListener('blur', saveSettings);
  maxActionsEl.addEventListener('blur', saveSettings);

  // 监听storage变化
  chrome.storage.onChanged.addListener(function(changes, areaName) {
    if (areaName === 'local' && (changes.isRecording || changes.recordedActions)) {
      updateStatus();
    }
  });

  // 初始化
  loadSettings();
  updateStatus();
  
  // 定期更新状态和统计
  setInterval(() => {
    updateStatus();
  }, 5000);
  
  console.log('选项页面已初始化');
}); 